"use client";
import useLazyLoad from "@/hooks/lazyLoad";
import { BaseHandlerProps, BaseProps } from "@/types/baseProps";
import React, { CSSProperties, MediaHTMLAttributes, useEffect, useRef, useState } from "react";
import Loading from "../../UI/Loading";
import { cn, sn } from "@/lib/util";
import SmallText from "../../UI/SmallText";
import { ReloadOutlined } from "@ant-design/icons";
import { VideoCameraOutlined } from "@ant-design/icons";
import { ColorVideoIcon } from "../../UI/MyIcon";
interface VideoProps extends BaseProps, BaseHandlerProps {
  /**视频宽度，不传递则根据className或style，默认100% */
  width?: number;
  /**视频高度(预估) 视频加载成功后，将根据宽度自适应高度。这个仅作为占位符的高度。不传递将与width相同(正方形占位图) */
  predictHeight?: number;
  /**视频路径 */
  src: string;
  /**是否开启播放控件，默认开始 */
  controls?: boolean;
  /**给video的style */
  videoStyle?: CSSProperties;
  /**给video的class */
  videoClassName?: string;
  /**占位符的背景色 */
  bgColor?: string;
  /**是否需要懒加载，默认开启 */
  lazy?: boolean;
  /**其它video原生props */
  otherProps?: MediaHTMLAttributes<any>;
}
/**视频组件 */
export default function Video({
  src,
  controls = true,
  width,
  style = {},
  className,
  videoStyle = {},
  videoClassName,
  bgColor = "#f5f5f5",
  predictHeight,
  lazy = true,
  otherProps,
  onClick,
}: VideoProps) {
  const outRef = useRef<HTMLDivElement>(null);
  const [loaded, setLoaded] = useState(false); //视频是否加载完成？ （加载成功失败都算完成）
  const [realSrc, setRealSrc] = useState<string>(); //存放展示的src，如果还没到视口就不展示
  const [err, setErr] = useState(false); //是否加载失败

  const lazyRef = useRef(lazy);

  ///懒加载主逻辑 即使外部设置了不需要懒加载，还是会调用这个回调函数，不过没什么副作用。
  useLazyLoad(outRef, () => {
    setRealSrc(src);
    lazyRef.current = false; //懒加载仅一次
  });

  useEffect(() => {
    //不需要懒加载的，就立即加载
    if (!lazyRef.current) {
      // console.log("立即加载 ");
      setRealSrc(src);
      setTimeout(() => {
        setLoaded(true); //开发服务器热更新后不会触发onload，手动触发
      }, 500);
    }
    return () => {
      setLoaded(false);
      setRealSrc(undefined);
      setErr(false);
    };
  }, [src]);

  /**刷新 - 加载失败时，点击可以尝试重新加载视频 */
  const reload = () => {
    setLoaded(false);
    setErr(false);
    setRealSrc(src + "?" + new Date().getTime());
  };

  return (
    <div
      onClick={onClick}
      className={cn(className, "rounded")}
      ref={outRef}
      style={sn(style, {
        width,
        height: loaded ? `` : `${predictHeight || width}px`,
        backgroundColor: loaded && !err ? "transparent" : bgColor,
      })}
    >
      {/* 加载中 */}
      {(!loaded || !realSrc) && (
        <div className={cn(videoClassName, "w-full h-full flexCenter relative")} style={videoStyle}>
          <Loading>
            <ColorVideoIcon size={60} />
          </Loading>
        </div>
      )}

      {/* 正常展示视频 */}
      {!err && realSrc && (
        <video
          style={sn(videoStyle, { display: loaded ? "block" : "none" })} //只有加载成功才显示
          src={realSrc}
          controls={controls}
          className={videoClassName}
          onCanPlay={() => {
            // console.log("@加载成功", realSrc);
            setLoaded(true);
          }}
          onError={() => {
            // console.log("加载失败", realSrc);
            setErr(true);
            setLoaded(true);
          }}
          {...otherProps}
        />
      )}

      {/* 加载失败 */}
      {err && (
        <div
          className={cn(videoClassName, `w-full h-full flexCenter flex-col outBox `)}
          style={sn(videoStyle, { height: `${predictHeight || width}px` })}
        >
          {/* <img
            src="/logo.png"
            className="my-2"
            style={{ width: `calc(${width ? `${width}px` : "100%"}  / 3.5)`, height: `calc(${width ? `${width}px` : "100%"}  / 3.5)` }}
            alt="加载失败"
          /> */}
          <ColorVideoIcon size={width ? width / 3.5 : 50} />
          <SmallText className="my-2">视频加载失败</SmallText>
          <ReloadOutlined onClick={reload} className="cursor-pointer" style={{ color: "#8e99a9" }} />
        </div>
      )}
    </div>
  );
}
